package com.cloudlead.common.lang.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象的序列化和反序列化
 * 
 * @author dean.lu
 * 
 */
public class ObjectSerializeUtils {

	/**
	 * 从字节数组反序列化成对象
	 * 
	 * @param bs
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object readObjectFromByteArray(byte[] bs) throws IOException,
			ClassNotFoundException {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(bs));
			Object value = ois.readObject();
			return value;
		} finally {
			if (null != ois) {
				ois.close();
			}
		}
	}

	/**
	 * 将对象序列化成字节数组
	 * 
	 * @param value
	 * @return
	 * @throws IOException
	 */
	public static byte[] writeObjectToByteArray(Object value)
			throws IOException {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream oos = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(value);
			oos.flush();
			return bos.toByteArray();
		} finally {
			if (null != bos) {
				bos.close();
			}
			if (null != oos) {
				oos.close();
			}
		}
	}

}
